<?php

class common {
	public $unicode = array(
			'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
			'd'=>'đ',
			'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
			'i'=>'í|ì|ỉ|ĩ|ị',
			'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
			'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
			'y'=>'ý|ỳ|ỷ|ỹ|ỵ',
			'A'=>'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
			'D'=>'Đ',
			'E'=>'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
			'I'=>'Í|Ì|Ỉ|Ĩ|Ị',
			'O'=>'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
			'U'=>'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
			'Y'=>'Ý|Ỳ|Ỷ|Ỹ|Ỵ',
		);

	public function __construct(){
		$this->x =& get_instance();
	}

	public function captcha(){
		$k = $this->x->captcha();
		echo form_hidden('captcha_key',$k).
			img(array(
				'src' => '/assets/images/captcha/'.$k.'.jpg',
				'alt' => 'Captcha image',
				'class' => 'captcha_image'
			));
	}

	public function flash(){
		$type = array('success','error','warning','alert');
		$mess = null;

		//flashdata session
		if(empty($this->x->data['flash'])):
			foreach($type as $v):
				$mess = $this->x->session->flashdata($v);
				if(!empty($mess))
					break;
			endforeach;
		//flash data variable in view
		else:
			$v = key($this->x->data['flash']);
			$mess = $this->x->data['flash'][$v];
		endif;

		if(empty($mess))
			return;

		echo '<div class="row"><div class="alert alert-'.($v=='error'?'danger':$v).' col-md-12">
		<a href="#" class="close" data-dismiss="alert">&times;</a><h4>'.ucfirst($v).':</h4> '.htmlspecialchars($mess).'</div></div>';
	}

	public function auth_anchor($url = null, $text = null, $attr = null, $escape = true){
		if(empty($url))
			return null;

		if($escape)
			$text = html_escape($text);

		//escape url last /character
		$url_pieces = explode('/', rtrim($url,'/'));
		if(!empty($url_pieces)):
			$url_pieces[] = url_title($this->remove_accents(array_pop($url_pieces)));
			$url = implode('/',$url_pieces);
		endif;

		$url = $this->remove_accents($url);
		return anchor('/'. $url, $text, $attr);
	}

	public function sortRow($id, $name, $type = 'alpha', $create_link = true){
		$reverseOrder = 'desc';
		$sortOrder = null;

		$id_list = @$this->x->paginate['sortList'][$id];
		if($this->x->data['pagination_sortBy'] == $id_list):
			$sortOrder = $this->x->data['pagination_sortOrder'];
			$reverseOrder = ($sortOrder == 'asc') ? 'desc' : 'asc';
		endif;

		switch($type):
			case 'numeric': break;
			case 'amount': break;
			default:
				$type = 'alpha';
		endswitch;

		if($create_link)
			return anchor(
				$this->x->data['pagination_nullLink'].'/'.$id.'/'.$reverseOrder,
				$name,'class="sortRow '.$type.'_'.$sortOrder.'"'
			);
		else
			return 'sortRow '.$type.'_'.$sortOrder;
	}

	public function remove_accents($str){
		$unicode = $this->unicode;
		foreach($unicode as $nonUnicode=>$uni)
			$str = preg_replace("/($uni)/i", $nonUnicode, $str);
		$str = preg_replace('#[^a-zA-Z0-9]#', '-', $str);
		$str = preg_replace('#-+#', '-', trim($str,'-'));
		return $str;
	}

	public function accents(){
		$unicode = $this->unicode;
		$data = null;
		foreach($unicode as $v):
			$v = str_replace('|', '', $v);
			$data .= $v.strtoupper($v);
		endforeach;
		return $data;
	}
	public function label($status, $text = null){
		switch($status):
			case 2: $label = 'success';break;
			case 0:	$label = 'danger';break;
			default:	$label = 'warning';
		endswitch;

		return '<label class="label label-'.$label.'">'.html_escape($text).'</label>';
	}

	public function nav_active($controller=null){
		return ($this->x->router->class == $controller)?'active':null;
	}

	public function bbcode($str){
		$find = array(
		  "'\[img\](.*?)\[/img\]'i",
		  "'\[url\](.*?)\[/url\]'i",
		  "'\[url=(.*?)\](.*?)\[/url\]'i",
		  "'\[email=(.*?)\](.*?)\[/email\]'i",
		  "'\[youtube\](.*?)\[/youtube\]'i",

		  "'\[ul\](.*?)\[/ul\]'is","'\[li\](.*?)\[/li\]'is","'\[ol\](.*?)\[/ol\]'is",

		  "'\[table\](.*?)\[/table\]'is",
		  "'\[tr\](.*?)\[/tr\]'is",
		  "'\[td\](.*?)\[/td\]'is",

		  "'\[hr\]'i",
		);

		$replace = array(
		  '<img src="\1" alt="" />',
		  '<a href="\1">\1</a>',
		  '<a href="\1">\2</a>',
		  '<a href="mailto:\1">\2</a>',
		  '<iframe width="420" height="315" src="http://www.youtube.com/embed/\1" frameborder="0" allowfullscreen></iframe>',

		  '<ul>\1</ul>','<li>\1</li>','<ol>\1</ol>',

		  '<table>\1</table>',
		  '<tr>\1</tr>','<td>\1</td>',

		  '<hr />'
		);

		$att  = array(
			'strong'=>'b','em'=>'i','u'=>'u','s'=>'s',
			'sub'=>'sub','sup'=>'sup',
			'p class="text-left"'=>'left','p class="text-right"'=>'right',
			'p class="text-center"'=>'center','p'=>'justify',
			'p dir="ltr"'=>'ltr','p dir="rtf"'=>'rtl',
			array(
				'open'=>'size=(\d+)','openR'=>'font size="\1"',
				'close'=>'size','closeR'=>'font'
			),
			array(
				'open'=>'color=\#(\w{3,6})',
				'openR'=>'span style="color:#$1"',
				'close'=>'color',
				'closeR'=>'span'
			),
			array(
				'open'=>'color=(\w+)',
				'openR'=>'span style="color:$1"',
				'close'=>'color',
				'closeR'=>'span'
			),
			array(
				'open'=>'font=(.*?)','openR'=>'span style="font-family:\1"',
				'close'=>'font','closeR'=>'span'
			)
		);

		foreach($att as $k => $v):
			if(is_array($v)):
				$open = $v['open'];$openR = $v['openR'];
				$close = $v['close']; $closeR = $v['closeR'];
			else:
				$open = $close = $v; $openR = $closeR = $k;
			endif;
			$str = preg_replace(
				"#\[".$open."\]#is",
				"<".$openR.">",$str
			);
			$str = preg_replace(
				"#\[\/".$close."\]#i",
				"</".$closeR.">", $str
			);
		endforeach;
		//$str = preg_replace($find, $replace, $str);
		return nl2br(preg_replace($find, $replace, $str));
	}

	public function recursive($category){
		foreach($category as $k => $v):
		?>
			<li id="list_<?php echo $v['id']; ?>">
				<div class="sortable-div"><span class="disclose"><span></span></span><?php 
					echo '<span class="inline-edit" data-pk="'.(int)$v['id'].'">'.
							html_escape($v['name']).
						'</span>';
				?></div><div class="label"><?php
					echo anchor('/admin/category/modify/'.$v['id'],'Edit').'&nbsp;'.
					anchor('/admin/category/delete/'.$v['id'],'Delete');
				?></div>
		<?php
			if(!empty($v['child'])):
				echo '<ol>';
				echo $this->recursive($v['child']);
				echo '</ol>';
			endif;
		?></li><?php
		endforeach;
	}

	public function category_drop($category, $depth = false){
		$drop = array();
		if(!$depth)
			$drop[0] = ' ';

		if(!empty($category))
			foreach($category as $k => $v):
				if(!isset($v['child']) && $depth):
					$drop[$v['id']] = $v['name'];
				else:
					if($depth):
						$drop[$v['name']] = array();
						if(empty($v['child'])){
							$drop[$v['name']][] = null;
							continue;
						}
						foreach($v['child'] as $childV)
							$drop[$v['name']][$childV['id']] = $childV['name'];

					else:
						$drop[$v['id']] = $v['name'];
					endif;
				endif;
			endforeach;
		return $drop;
	}

	public function end_nav($class = null, $func = null, $equal = true){
		$cur_class = $this->x->router->fetch_class();

		$css_class = false;
		if($cur_class == $class):
			$css_class = 'active';

			if(!empty($func)):
				$cur_func = $this->x->router->fetch_method();
				$css_class = false;
				if($func == $cur_func):
					if(!$equal)
						$css_class = false;
					else
						$css_class = 'active';
				else:
					if(!$equal)
						$css_class = 'active';
				endif;
			endif;
		endif;

		return $css_class;
	}

	public function phone($str){
		$strPhone = preg_replace("[^0-9]",'', $str);

	    if (strlen($strPhone) <= 9)
	        return $strPhone;

	    $strArea = substr($strPhone, 0, 3);
	    $strPrefix = substr($strPhone, 3, 3);
	    $strNumber = substr($strPhone, 6, 4);

	    $strPhone = $strArea."-".$strPrefix."-".$strNumber;

	    return ($strPhone);
	}
}
